import os
from db.config import db_maps_path
from db.db_connection_pool import get_connection, get_config
from common.write_file import write_json
from common.read_file import read_json


def update_db_map():
    db_connection = get_connection()
    sql = "SELECT TABLE_SCHEMA, TABLE_NAME from information_schema.TABLES"
    cursor = db_connection.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    maps = {}
    table_db_maps = []
    for single_data in data:
        db_name = single_data['TABLE_SCHEMA']
        table_name = single_data['TABLE_NAME']
        table_db_maps.append("%s.%s" % (db_name, table_name))
    maps['table_db_maps'] = table_db_maps
    column_table_db_maps = {}
    sql = 'SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM information_schema.COLUMNS'
    cursor = db_connection.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    for single_data in data:
        db_name = single_data['TABLE_SCHEMA']
        table_name = single_data['TABLE_NAME']
        column_name = single_data['COLUMN_NAME']
        tmp_table_name = "%s.%s" % (db_name, table_name)
        if tmp_table_name not in column_table_db_maps:
            column_table_db_maps[tmp_table_name] = []
        column_table_db_maps[tmp_table_name].append(column_name)
    maps['column_table_db_maps'] = column_table_db_maps
    write_json(maps, get_db_maps_path())
    pass


def get_db_maps_path():
    db_config = get_config()
    host = db_config['host']
    return db_maps_path + host + '.json'
    pass


def get_db_maps():
    path = get_db_maps_path()
    if not os.path.isfile(path):
        return []
    return read_json(path)['table_db_maps']
    pass


def get_column_table_db_maps():
    path = get_db_maps_path()
    if not os.path.isfile(path):
        return {}
    return read_json(path)['column_table_db_maps']
    pass


def get_column_by_table(table_name):
    maps = get_column_table_db_maps()
    if table_name not in maps:
        return []
    return maps[table_name]
    pass
